package com.example.blogdevelop.service.impl;

import com.example.blogdevelop.entity.User;
import com.example.blogdevelop.mapper.UserMapper;
import com.example.blogdevelop.service.MailService;
import com.example.blogdevelop.vo.UserVo;
import com.example.blogdevelop.vo.UserVoToUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.*;
import javax.servlet.http.HttpSession;
import java.util.Random;

@Service
public class MailServiceImpl implements MailService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSenderImpl mailSender;

    // application.properties配置的值
    @Value("${spring.mail.username}")
    private String from;

    @Value("${spring.mail.password}")
    private String password;
    /**
     * 给前端输入的邮箱，发送验证码
     * @param email
     * @param session
     * @return
     */
    @Override
    public boolean sendMimeMail( String email, HttpSession session) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();

            mailMessage.setSubject("验证码邮件");//主题
            //生成随机数
            String code = randomCode();

            //将随机数放置到session中
            session.setAttribute("email",email);
            session.setAttribute("code",code);

            mailMessage.setText("您收到的验证码是："+code);//内容

            mailMessage.setTo(email);//发给谁

            mailMessage.setFrom(from);//你自己的邮箱


            mailSender.send(mailMessage);//发送

            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 随机生成6位数的验证码
     * @return String code
     */
    @Override
    public String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for(int i = 0;i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    /**
     * 检验验证码
     * @param userVo
     * @param session
     * @return
     */
    @Override
    public boolean registered(UserVo userVo, HttpSession session) {
        // 获取session中的验证信息
        String email = (String) session.getAttribute("email");
        String code = (String) session.getAttribute("code");

        // 获取表单中的提交的验证信息
        String voCode =  userVo.getCode();

        //如果emial数据为空或者不一致都失败
        if(email == null || email.isEmpty()) {
            //return "error,请重新注册";
            return false;
        }else if (!code.equals(voCode)){
            //return "error,请重新注册";
            return false;
        }

        // 保存数据
        User user = UserVoToUser.toUser(userVo);

        // 将数据写进数据库
        userMapper.insert(user);


        // 跳转成功页面
        return true;
    }

}